<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <SearchForm
          v-show="showSearch"
          v-model="queryParams"
          :options="options.formOps"
          @onQuery="getList"
        >
        </SearchForm>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['preventionUnit:create']"
              >新增</el-button
            >
          </el-col>

          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>
        <Table
          ref="table"
          :auto-featch="true"
          :fetch-data="fetchData"
          :options="options.table"
          actionWidth="260"
        >
          <template #state="{ row }">
            {{ row.state == 0 ? "是" : "否" }}
          </template>
          <template #deviceId="{ row }"> {{ row.deviceName }} </template>
          <template #default>
            <el-table-column prop="state" label="是否启用" align="center">
              <template #default="{ row }">
                {{ row.state == "0" ? "是" : "否" }}
              </template>
            </el-table-column></template
          >
          <template #actionButton="{ row }">
            <el-button
              type="text"
              @click="handleCode(row)"
              v-hasPermi="['preventionUnit:qrcode']"
              >二维码</el-button
            >
            <el-button
              type="text"
              icon="Edit"
              @click="handleEdit(row)"
              v-hasPermi="['preventionUnit:update']"
              >修改</el-button
            >
            <el-button type="text" @click="handleChange(row)">{{
              row.state == "0" ? "停用" : "启用"
            }}</el-button>
            <el-button
              type="text"
              icon="Delete"
              style="color: red"
              @click="handleDel(row)"
              v-hasPermi="['preventionUnit:delete']"
              >删除</el-button
            >
            <el-button type="text" @click="handleHistory(row)"
              >停用记录</el-button
            >
          </template></Table
        >
        <DialogVform
          :formJson="formJson"
          ref="dialogVform"
          :slots="['deptName', 'planName', 'userName']"
          @onSubmit="onSubmit"
          :title="dialogType == 'add' ? '新增单元位置' : '修改单元位置'"
        >
          <template #deptName>
            <el-form-item
              label="责任部门"
              prop="planDeptId"
              label-position="right"
            >
              <TreeSelect
                v-model="form.planDeptId"
                :options="deptTree"
                @change="changeDept"
                style="width: 100%"
              >
              </TreeSelect>
            </el-form-item>
          </template>
          <template #userName>
            <el-form-item label="责任人" prop="userId" label-position="right">
              <el-select
                @change="userIdChange"
                style="width: 100%"
                v-model="form.userId"
              >
                <el-option
                  v-for="user in userList"
                  :value="user.userId"
                  :label="user.nickName"
                ></el-option>
              </el-select>
            </el-form-item>
          </template>
          <template #planName>
            <el-form-item label="处置方案名称">
              <el-input
                v-model="form.planName"
                readonly
                @click="onInnerOpen"
              ></el-input>
            </el-form-item>
          </template>
        </DialogVform>
      </el-col>
      <el-dialog v-model="imgDialog" width="380px" center>
        <img style="margin: 0 auto" :src="codeUrl" alt="" />
        <template #footer>
          <el-button
            type="primary"
            @click="handleDownLoad(downloadUrl, '二维码.png')"
            >下载</el-button
          >
        </template>
      </el-dialog>

      <el-dialog v-model="historyDialog" title="停用历史">
        <el-table :data="historyList">
          <el-table-column property="stopTime" label="停用开始时间" />
          <el-table-column property="startTime" label="停用结束时间" />
          <el-table-column property="stopInfo" label="停用原因" />
        </el-table>
      </el-dialog>
    </el-row>
  </div>
</template>

<script setup>
import Table from "@/components/Table/index.vue";
import SearchForm from "@/components/searchForm/index";
import DialogVform from "@/components/dialogVform/index";
import formJson from "./components/options.json";
import { apis as ZZWZ } from "@/api/tool/zzgl.js";
import { ElMessageBox } from "element-plus";
import { apis as APIS } from "@/api/fxfjgk/dywzwh.js";
import { useAsyncData, useFormJsonNew } from "@/views/hooks/useAsyncData.js";
import TableSelect from "@/components/tableSelect";

import { deptTreeSelect, listUser } from "@/api/system/user";
const imgDialog = ref(false);
const historyDialog = ref(false);
const historyList = ref([]);
const codeUrl = ref("");
const downloadUrl = ref("");
const handleCode = (row) => {
  imgDialog.value = true;
  downloadUrl.value = row.zxingUrl;
  codeUrl.value = "/dev-api/file/download?url=" + row.zxingUrl;
};
const { proxy } = getCurrentInstance();

const ops = useFormJsonNew(formJson, {
  sort: [],
  sortable: [],
});
const options = reactive({
  table: ops.filter((item) => !["deptName", "userName"].includes(item.prop)),
  formOps: ops.filter((i) =>
    ["deptName", "unitNamec", "longitudec", "state"].includes(i.prop)
  ),
});
const plugSubmit = (data) => {
  return {
    ...data,
    deviceName: zzwzList.value[data.deviceId],
  };
};
const showSearch = ref(true);
const dialogVform = ref();
const table = ref();
const tableSelect = ref();
const userList = ref([]);
const changeDept = (val, label) => {
  form.value.deptName = label;
  form.value.deptId = val;
  if (val) {
    listUser({
      pageNum: 1,
      pageSize: 5000000,
      deptId: val,
    }).then((res) => {
      userList.value = res.rows;
    });
  }
};
const handleHistory = (row) => {
  historyDialog.value = true;
  APIS.stopItem({ unitId: row.id }).then((res) => {
    historyList.value = res.rows;
  });
};
const handleChange = (row) => {
  ElMessageBox.prompt(
    row.state == "1" ? "" : "停用原因",
    row.state == "1" ? "是否启用" : "停用",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      showInput: row.state == "1" ? false : true,
    }
  )
    .then(({ value }) => {
      if (row.state == "1") {
        APIS.start({ id: row.id, state: "0" }).then((res) => {
          if (res.code == 200) {
            proxy.$modal.msgSuccess("已启用");
            getList();
          }
        });
      } else {
        APIS.stop({ id: row.id, stopInfo: value, state: "1" }).then((res) => {
          if (res.code == 200) {
            proxy.$modal.msgSuccess("已停用");
            getList();
          }
        });
      }
    })
    .catch(() => {});
};
const userIdChange = (val) => {
  if (val) {
    const user = userList.value.find((user) => user.userId === val);
    form.value.userName = user.nickName;
  } else {
    form.value.userName = "";
  }
};
const plugEdit = (row) => {
  // form.value = { ...row };
  form.value.planDeptId = row.deptId || "";
  form.value.planDeptName = row.deptName || "";
  form.value.deptId = row.deptId || "";
  form.value.deptName = row.deptName || "";
  form.value.userId = row.userId || "";
  form.value.userName = row.userName || "";
  changeDept(form.value.planDeptId, form.value.planDeptName);
  // changeMeasuresOne(form.value.measuresOne);
};
const plugAdd = () => {
  form.value.deptId = "";
  form.value.deptName = "";
};
const {
  onSubmit,
  fetchData,
  dialogType,
  handleAdd,
  handleEdit,
  getList,
  handleDel,
  queryParams,
  form,
  handleDownLoad,
} = useAsyncData({
  APIS,
  formJson,
  dialogVform,
  table,
  proxy,
  plugEdit,
  plugAdd,
  plugSubmit,
});
const zzwzList = ref({});
const pageForm = {
  pageNum: 1,
  pageSize: 9999999999999999,
};
const deptTree = ref([]);
onMounted(() => {
  ZZWZ.query(pageForm).then((res) => {
    res.rows.forEach((item) => {
      zzwzList.value[item.id] = item.deviceName;
    });
  });
  deptTreeSelect().then((response) => {
    deptTree.value = response.data;
  });
});
</script>

<style lang="scss" scoped>
::v-deep.el-form-item__label {
  text-align: right !important;
}
</style>
